package cn.lcfms.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class HttpUtils {
    /**
     * 使用GET方法从WEB上获取信息，并将数据保存到一个字节数组中
     * @param  urlpath url地址
     * @return 字节数组
     * @throws Exception
     */
	public static byte[] getdata(String urlpath)throws Exception {
        URL url=new URL(urlpath);
        HttpURLConnection conn=(HttpURLConnection)url.openConnection();//基于HTTP连接的一个对象
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode()==200){
        	InputStream inputStream=conn.getInputStream();
        	BufferedInputStream buffer=new BufferedInputStream(inputStream);
        	byte[] data=HttpUtils.stream_to_byte(buffer);     	
            inputStream.close();
        	return data;
        }
        return null;
	}
	 /**
     * 模拟浏览器使用GET方法从WEB上获取信息，并将数据保存到一个字节数组中
     * @param  urlpath url地址
     * @return 字节数组
     * @throws Exception
     */
	public static String browser(String urlpath)throws Exception {
        URL url=new URL(urlpath);
        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
    	conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
        if(conn.getResponseCode()==200){
        	InputStream inputStream=conn.getInputStream();
        	BufferedInputStream buffer=new BufferedInputStream(inputStream);
        	byte[] data=HttpUtils.stream_to_byte(buffer);     	
            inputStream.close();
        	return new String(data);
        }
        return null;
	}
	/**
	 * 从POST方法向WEB发送数据,并返回一段字符串
	 * @param map 将要发送的参数，键位KEY，值为VALUE
	 * @param url url地址
	 * @return
	 * @throws Exception
	 */
    public static String postdata(Map<String, Object> map,String url) throws Exception{
    	URL Url=new URL(url);
    	HttpURLConnection conn=(HttpURLConnection)Url.openConnection();
    	conn.setConnectTimeout(30000);
    	conn.setRequestMethod("POST");
    	conn.setDoOutput(true);
    	StringBuffer params = new StringBuffer();
    	for(String key:map.keySet()){
    		 Object val= map.get(key);   	
    		 val=URLEncoder.encode(String.valueOf(map.get(key)),"utf-8");  
    	     params.append(key).append("=").append(val).append("&");
    	}    	
        byte[] data = params.substring(0, params.length()-1).getBytes();       
    	conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    	conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    	OutputStream outputStream=conn.getOutputStream();
    	outputStream.write(data);
    	outputStream.flush();  
    	outputStream.close();      	
    	if(conn.getResponseCode()==200){
    		InputStream stream=conn.getInputStream();  	
    		byte[] data_r=HttpUtils.stream_to_byte(stream);
    		return new String(data_r,0,data_r.length,"utf-8");		
    	}else{
    		return "";
    	}	

    }
    /**
     * 获取WEBservice服务,返回的是一段从WEB服务器传来的输入流
	 * @param data 将要发送的发送数据
	 * @param url url地址
     */
    public static byte[] webservice(String url,Map<String, String> paramMap,Map<String, String> cookieMap)throws Exception{	
    	URL Url=new URL(url);
    	HttpURLConnection conn=(HttpURLConnection)Url.openConnection();
    	conn.setConnectTimeout(30000);
    	conn.setRequestMethod("POST");
    	conn.setDoOutput(true);
    	StringBuffer params = new StringBuffer();
    	byte[] data="".getBytes();
    	if(paramMap!=null){
    		for(String key:paramMap.keySet()){
       		 Object val= paramMap.get(key);   	
       		 val=URLEncoder.encode(String.valueOf(paramMap.get(key)),"utf-8");  
       	     params.append(key).append("=").append(val).append("&");
    		}  
    	    data = params.substring(0, params.length()-1).getBytes();  
    	}  	
    	if(cookieMap!=null){
        	String cookies="";
    		StringBuffer p = new StringBuffer();
	    	for(String key:cookieMap.keySet()){
	    		 Object val= cookieMap.get(key);   	
	    		 val=URLEncoder.encode(String.valueOf(cookieMap.get(key)),"utf-8");  
	    	     p.append(key).append("=").append(val).append(";");
	    	}      
	    	cookies=p.substring(0, p.length()-1);
	    	conn.setRequestProperty("Cookie",cookies);  
    	}	
         
    	conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    	conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    	OutputStream outputStream=conn.getOutputStream();
    	outputStream.write(data);
    	outputStream.flush();  
    	outputStream.close();      	
    	if(conn.getResponseCode()==200){
    		InputStream stream=conn.getInputStream();  	
    		byte[] data_r=HttpUtils.stream_to_byte(stream);
    		return data_r;
    	}else{
    		return null;
    	}	
    }
    /*
     * 将一个输入流转换成字节数组
     */
	public static byte[] stream_to_byte(InputStream stream)throws Exception{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        byte[] bs = new byte[1024];   
        int len = -1;  
        while ((len = stream.read(bs)) != -1) {  
            bos.write(bs, 0, len);  
        }  
        byte[] b = bos.toByteArray();  
        bos.close();
        return b;
    }
}
